﻿using System;
using Newtonsoft.Json;
using System.IO;
using Newtonsoft.Json.Converters;

namespace Sissonix.ExtRest.Serialization
{
    /// <summary>
    /// Class for deserializing/serializing to JSON.
    /// </summary>
    public class JsonSerializer : ISerializer
    {
        public string ContentType
        {
            get { return MimeTypes.APPLICATION_JSON; }
        }

        public object Deserialize(string value, Type type)
        {
            //MWS
            //return JavaScriptConvert.DeserializeObject(value, type);
            return JsonConvert.DeserializeObject(value, type);
        }

        public virtual string Serialize(object objectToSerialize)
        {
            //return JsonConvert.SerializeObject(objectToSerialize);

            Newtonsoft.Json.JsonSerializer jsonSerializer = new Newtonsoft.Json.JsonSerializer();
            
            //MWS Changed to Ignore from Error
            jsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

            StringWriter sw = new StringWriter();
            jsonSerializer.Serialize(sw, objectToSerialize);
            return sw.ToString();

            ////MWS - Used the JsonSerialized instead of SerializeObject
            ////to provide control of the ReferenceLoopHandling.
            //Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();

            //serializer.Converters.Add(new JavaScriptDateTimeConverter());
            //serializer.NullValueHandling = NullValueHandling.Ignore;

            //using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
            //using (JsonWriter writer = new JsonTextWriter(sw))
            //{
            //    serializer.Serialize(writer, objectToSerialize);
            //    return writer.ToString();
            //}

            ////MWS 
            ////return JavaScriptConvert.SerializeObject(objectToSerialize);
        }
    }
}
